# -*- coding: utf-8 -*-
# @Time    : 2022/11/7 20:36
# @Author  : 限量老
import os
from django import forms
from django.conf import settings
from django.http import HttpResponse
from django.shortcuts import render, redirect

from app01 import models
from app01.utils.bootstrap样式 import BootStrapForm, BootStrapModelForm


def upload_list(request):
    if request.method == 'GET':
        return render(request, 'upload_list.html')
    file_obj = request.FILES.get('avatar')  # 'avatar':要获取的上传文件
    print(file_obj)  # 文件 名

    with open(file_obj.name, mode='wb') as f:
        for chunk in file_obj.chunks():  # 读取一点写一点
            f.write(chunk)

    return HttpResponse('....')


class UpForm(BootStrapForm):
    bootstrap_exclude_fields = ['img']  # 设定不应用样式的 项

    name = forms.CharField(label='姓名')
    age = forms.IntegerField(label='年龄')
    img = forms.FileField(label='头像')


def upload_form(request):
    title = 'Form上传'
    if request.method == 'GET':
        form = UpForm()
        return render(request, 'upload_form上传表单.html.', {'form': form, 'title': title})

    form = UpForm(data=request.POST, files=request.FILES)  # 表单数据部分+文件
    if form.is_valid():
        print(form.changed_data)
        # 读取到内容,处理每个字段的数据:
        # 1.读取图片内容,写入到文件夹中,获取路径
        imgage_object = form.cleaned_data.get('img')

        media_path = os.path.join(settings.MEDIA_ROOT, imgage_object.name)  # 绝对路径
        # media_path=os.path.join('media', imgage_object.name)  # 相对路径

        with open(media_path, 'wb') as f:
            for chunk in imgage_object.chunks():
                f.write(chunk)

        # 将图片路径写入到数据库中
        models.Boss.objects.create(
            name=form.cleaned_data['name'],
            age=form.cleaned_data['age'],
            img=media_path, )
        return HttpResponse('...')

    return render(request, 'upload_form上传表单.html.', {'form': form, 'title': title})


class UpModelForm(BootStrapModelForm):
    bootstrap_exclude_fields = ['img']  # 设定不应用样式的 项

    class Meta:
        model = models.City
        fields = '__all__'


def upload_modelform(request):
    """上传文件和数据(modelform)"""
    title = 'ModelForm上传文件'
    if request.method == 'GET':
        form = UpModelForm()
        return render(request, 'upload_form上传表单.html', {'form': form, 'title': title})

    form = UpModelForm(data=request.POST, files=request.FILES)
    if form.is_valid():
        # 对于文件:自动保存;
        # 字段+上传路径写入到数据库
        form.save()

        return redirect('/city/list/')
    return render(request, 'upload_form上传表单.html.', {'form': form, 'title': title})